package chapter1.String.task;

/*
9：定义一个字符串，找出其中最长的重复字符串，比如
abcfabc,则结果是abc；比如 afkafk,则结果是afk;
abc,没有；abcac,结果是a;有重复的，找到一个即可。
 */
public class Task9 {
    public static void main(String[] args) {
        String s = "abcfabc";
        String s1 = "";
        String s2 = "";
        int maxCount = 0, count = 0;
        for (int i = 0; i < s.length(); i++) {
            count = getcount(s.charAt(i) + "", s);
            if (count > maxCount) {
                maxCount = count;
                s2 = s.charAt(i) + "";
            }
        }
        for (int i = 0; i < s.length() / 2; i++) {
            s1 += s.charAt(i);
            count = getcount(s1, s);
            if (count >= maxCount) {
                maxCount = count;
                s2 = s1;
            }
        }

        if (maxCount > 1)
            System.out.println("最长的重复字符串为：" + s2 + ",重复次数为：" + maxCount + "次");
        else
            System.out.println("无重复字符串");

    }


    public static int getcount(String a, String b) {
        int index = 0, count = 0;
        while ((index = b.indexOf(a)) != -1) {
            b = b.substring(index + a.length());//截取未被查找到目标字符串的字符串
            count++;
        }
        return count;
    }

}
